package com.airjoy.server {
	import com.airjoy.server.events.AIRJoyServerEvent;
	import com.airjoy.server.events.JoyServerEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.ServerSocketConnectEvent;
	import flash.net.ServerSocket;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	/**
	 * ...
	 * @author Ricardo Teixeira
	 */
	public class JoyServer extends EventDispatcher {
		
		private var port:uint;
		private var clients:Vector.<Socket>;
		
		public function JoyServer(port:uint = 6667) {
			this.port = port;
			this.clients = new Vector.<Socket> ();
		}
		
		public function start ():void{
			
			this.server = new ServerSocket ();			
			this.server.addEventListener (Event.CONNECT, onConnect);
			
			try {
				this.server.bind (this.port);
				this.server.listen();
			} catch (e:Error) {
				trace (e.message, "Error in connect");
			}			
		}
		
		
		public function broadcast (client:Socket):void {
			var buffer:ByteArray = new ByteArray();
			var clientSocket:Socket = client;
            clientSocket.readBytes( buffer, 0, clientSocket.bytesAvailable );
			
			var id:int = this.clientes.indexOf (cliente);
			
			for (var i:int = 0; i < this.clients.length; i++) {
				clientSocket = this.clientes[i] as Socket;
				clientSocket.writeUTFBytes ( buffer.toString() );
				clientSocket.flush ();
			}
		}		
		
		private function onConnect(e:ServerSocketConnectEvent):void {
			var client:Socket = Socket (e.socket);
			client.addEventListener (ProgressEvent.SOCKET_DATA, onData);
			client.addEventListener (Event.CLOSE, onCloseClient);
			client.addEventListener (IOErrorEvent.IO_ERROR, onErrorClient);
			client.addEventListener (SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			
			this.clients.push (client);
			
			var event:JoyServerEvent = new JoyServerEvent (JoyServerEvent.CONNECT, client);
			this.dispatchEvent ( event );
		}
		
		public function get numClients ():uint {
			return this.clients.length;
		}
		
		private function onErrorClient(e:IOErrorEvent):void {
			
		}
		
		private function onCloseClient(e:Event):void {
			var client:Socket = e.target as Socket;
			var id:int = this.clients.indexOf (client);
			
			if (id != -1) {
				this.clients.splice (id, 1);
			
				var event:JoyServerEvent = new JoyServerEvent (JoyServerEvent.DISCONNECT, client);
				this.dispatchEvent ( event );
			}
		}
		
		private function onSecurityError(e:SecurityErrorEvent):void {
			
		}
		
	}

}